package com.xopencode.io.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @author Mcb
 * @date 2022/5/9
 * @apiNote 聊天室客户端
 */
public class ChatClient {

    private final String HOSTNAME = "127.0.0.1";
    private final int PORT = 10086;
    private SocketChannel socketChannel;
    private Selector selector;
    private String userName;

    public ChatClient(){
        try {
            socketChannel = SocketChannel.open(new InetSocketAddress(HOSTNAME,PORT));
            socketChannel.configureBlocking(false);
            selector = Selector.open();
            socketChannel.register(selector, SelectionKey.OP_READ);
            userName=socketChannel.getLocalAddress().toString();
            System.out.println(userName+" is ready!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendInfo(String info){
        try {
            info=userName+":"+info;
            socketChannel.write(ByteBuffer.wrap(info.getBytes(StandardCharsets.UTF_8)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void readInfo(){
        try {
            int readyChannel = selector.select();
            if (readyChannel>0){
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    if (key.isReadable()){
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        channel.read(buffer);
                        String mag = new String(buffer.array());
                        System.out.println(mag);
                    }
                }
            }else{
                System.out.println("没有准备就绪的通道！");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ChatClient chatClient = new ChatClient();
        new Thread(()->{
            while (true){
                chatClient.readInfo();
            }
        }).start();

        Scanner input = new Scanner(System.in);
        while (input.hasNextLine()){
            String str = input.nextLine();
            chatClient.sendInfo(str);
        }
    }

}
